<template>
  <div>
    <!-- 登录模态框 -->
    <AuthModal
      :is-open="showLoginModal"
      title="登录到您的账户"
      @close="closeLogin"
    >
      <AuthForm
        :error="loginError"
        :success-message="loginSuccessMessage"
        :loading="loginLoading"
        :resend-loading="resendLoading"
        button-text="登录"
        loading-text="登录中..."
        google-button-text="使用Google登录"
        bottom-text="还没有账号？"
        bottom-link="#"
        bottom-link-text="立即注册"
        @submit="handleLoginSubmit"
        @google-auth="handleGoogleLogin"
        @resend-confirmation="handleResendConfirmation"
        @switch-mode="openRegister"
      >
        <!-- 邮箱输入 -->
        <UiInput
          id="login-email"
          label="邮箱地址"
          v-model="loginEmail"
          type="email"
          required
          placeholder="请输入邮箱地址"
        />

        <!-- 密码输入 -->
        <UiInput
          id="login-password"
          label="密码"
          v-model="loginPassword"
          type="password"
          required
          placeholder="请输入密码"
        />
      </AuthForm>
    </AuthModal>

    <!-- 注册模态框 -->
    <AuthModal
      :is-open="showRegisterModal"
      title="创建您的账户"
      @close="closeRegister"
    >
      <AuthForm
        :error="registerError"
        :success-message="registerSuccessMessage"
        :loading="registerLoading"
        button-text="注册"
        loading-text="注册中..."
        google-button-text="使用Google注册"
        bottom-text="已有账号？"
        bottom-link="#"
        bottom-link-text="立即登录"
        @submit="handleRegisterSubmit"
        @google-auth="handleGoogleRegister"
        @switch-mode="openLogin"
      >
        <!-- 用户名输入 -->
        <UiInput
          id="register-username"
          label="用户名"
          v-model="registerUsername"
          type="text"
          required
          placeholder="请输入用户名"
        />

        <!-- 邮箱输入 -->
        <UiInput
          id="register-email"
          label="邮箱地址"
          v-model="registerEmail"
          type="email"
          required
          placeholder="请输入邮箱地址"
        />

        <!-- 密码输入 -->
        <UiInput
          id="register-password"
          label="密码"
          v-model="registerPassword"
          type="password"
          required
          placeholder="请输入密码（至少6位）"
        />

        <!-- 确认密码输入 -->
        <UiInput
          id="register-confirmPassword"
          label="确认密码"
          v-model="registerConfirmPassword"
          type="password"
          required
          placeholder="请再次输入密码"
        />
      </AuthForm>
    </AuthModal>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../store/useUserStore'
import { storeToRefs } from 'pinia'
import AuthModal from './AuthModal.vue'
import AuthForm from './AuthForm.vue'
import { UiInput } from '../ui'

const router = useRouter()
const userStore = useUserStore()

// 从store获取模态框状态
const { showLoginModal, showRegisterModal } = storeToRefs(userStore)

// 登录表单数据
const loginEmail = ref('')
const loginPassword = ref('')
const loginLoading = ref(false)
const resendLoading = ref(false)
const loginError = ref('')
const loginSuccessMessage = ref('')

// 注册表单数据
const registerUsername = ref('')
const registerEmail = ref('')
const registerPassword = ref('')
const registerConfirmPassword = ref('')
const registerLoading = ref(false)
const registerError = ref('')
const registerSuccessMessage = ref('')

// 监听路由变化，自动关闭模态框
watch(() => router.currentRoute.value.path, () => {
  userStore.closeAllModals()
})

// 打开登录模态框
const openLogin = () => {
  userStore.openLoginModal()
  resetLoginForm()
}

// 打开注册模态框
const openRegister = () => {
  userStore.openRegisterModal()
  resetRegisterForm()
}

// 关闭登录模态框
const closeLogin = () => {
  userStore.closeLoginModal()
  resetLoginForm()
}

// 关闭注册模态框
const closeRegister = () => {
  userStore.closeRegisterModal()
  resetRegisterForm()
}

// 重置登录表单
const resetLoginForm = () => {
  loginEmail.value = ''
  loginPassword.value = ''
  loginError.value = ''
  loginSuccessMessage.value = ''
}

// 重置注册表单
const resetRegisterForm = () => {
  registerUsername.value = ''
  registerEmail.value = ''
  registerPassword.value = ''
  registerConfirmPassword.value = ''
  registerError.value = ''
  registerSuccessMessage.value = ''
}

// 处理登录提交
const handleLoginSubmit = async () => {
  if (!loginEmail.value || !loginPassword.value) {
    loginError.value = '请填写完整信息'
    return
  }

  loginLoading.value = true
  loginError.value = ''
  loginSuccessMessage.value = ''

  try {
    const { error: signInError } = await userStore.signIn(loginEmail.value, loginPassword.value)
    
    if (signInError) {
      loginError.value = (signInError as any).message || '登录失败，请检查邮箱和密码'
    } else {
      // 登录成功，关闭模态框
      closeLogin()
    }
  } catch (err) {
    loginError.value = '登录失败，请稍后重试'
  } finally {
    loginLoading.value = false
  }
}

// 处理注册提交
const handleRegisterSubmit = async () => {
  // 表单验证
  if (!registerUsername.value || !registerEmail.value || !registerPassword.value || !registerConfirmPassword.value) {
    registerError.value = '请填写完整信息'
    return
  }

  if (registerPassword.value !== registerConfirmPassword.value) {
    registerError.value = '两次输入的密码不一致'
    return
  }

  if (registerPassword.value.length < 6) {
    registerError.value = '密码长度至少6位'
    return
  }

  registerLoading.value = true
  registerError.value = ''
  registerSuccessMessage.value = ''

  try {
    const { error: signUpError } = await userStore.signUp(registerEmail.value, registerPassword.value)
    
    if (signUpError) {
      registerError.value = (signUpError as any).message || '注册失败，请稍后重试'
    } else {
      // 注册成功，显示确认邮件信息
      registerSuccessMessage.value = '注册成功！请检查您的邮箱并点击确认链接来激活账户。'
      registerError.value = ''
      // 清空表单
      resetRegisterForm()
    }
  } catch (err) {
    registerError.value = '注册失败，请稍后重试'
  } finally {
    registerLoading.value = false
  }
}

// 处理Google登录
const handleGoogleLogin = async () => {
  loginLoading.value = true
  loginError.value = ''
  loginSuccessMessage.value = ''

  try {
    const { error: googleError } = await userStore.signInWithGoogle()
    
    if (googleError) {
      loginError.value = (googleError as any).message || 'Google登录失败'
    } else {
      closeLogin()
    }
  } catch (err) {
    loginError.value = 'Google登录失败，请稍后重试'
  } finally {
    loginLoading.value = false
  }
}

// 处理Google注册
const handleGoogleRegister = async () => {
  registerLoading.value = true
  registerError.value = ''

  try {
    const { error: googleError } = await userStore.signInWithGoogle()
    
    if (googleError) {
      registerError.value = (googleError as any).message || 'Google注册失败'
    } else {
      closeRegister()
    }
  } catch (err) {
    registerError.value = 'Google注册失败，请稍后重试'
  } finally {
    registerLoading.value = false
  }
}

// 处理重发确认邮件
const handleResendConfirmation = async () => {
  if (!loginEmail.value) {
    loginError.value = '请先输入邮箱地址'
    return
  }

  resendLoading.value = true
  loginError.value = ''

  try {
    const { error: resendError } = await userStore.resendConfirmationEmail(loginEmail.value)
    
    if (resendError) {
      loginError.value = (resendError as any).message || '发送确认邮件失败'
    } else {
      loginSuccessMessage.value = '确认邮件已发送，请检查您的邮箱'
      loginError.value = ''
    }
  } catch (err) {
    loginError.value = '发送确认邮件失败，请稍后重试'
  } finally {
    resendLoading.value = false
  }
}

// 暴露方法给父组件
defineExpose({
  openLogin,
  openRegister,
  closeLogin,
  closeRegister
})
</script> 